<template>
  <BasicLayout>
    <template #wrapper>
      <div style="height:20px" />
      <menu-table ref="refBox" height="500" :table-data="tableData" :columns="columns">
        <template slot="buttonPermissions" slot-scope="scope">
          <div>
            <ysz-checkbox-group ref="btnRef" :boxs="scope.item.buttonPermissions" @update="update" />
          </div>
        </template>
        <template slot="name" slot-scope="scope">
          <el-checkbox v-if="scope.item.flag" v-model="scope.item.flag" false-label="uncheck" true-label="check" @change="checkSin(scope.item)">{{ scope.item.name }}</el-checkbox>
          <span v-else>{{ scope.item.name }}</span>
        </template>
      </menu-table>
      <el-row type="flex" justify="center">
        <el-button size="mini" type="primary" @click="save">保存</el-button>
        <el-button size="mini" @click="goBack">取消</el-button>
      </el-row>
    </template>
  </BasicLayout>
</template>
<script>
import { mapGetters } from 'vuex';
import { geRoleTree, addRoleRightButton } from '@/api/roleApi';
import menuTable from '../common/menu-table';
import yszCheckboxGroup from '../common/ysz-checkbox-group';
import { Message } from 'element-ui';
const columns = [
  {
    label: '菜单名称',
    prop: 'name',
    slot: true
  },
  {
    prop: 'buttonPermissions',
    label: '按钮权限',
    slot: true
  }
];
export default {
  components: {
    menuTable,
    yszCheckboxGroup
  },
  data() {
    return {
      columns: columns,
      tableData: [],
      subData: [],
      mp: new Map()
    };
  },
  // 监听属性 类似于data概念
  computed: {
    ...mapGetters([
      // 映射 this.count 为 store.state.count
      'name'
    ])
  },
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let { name } = this;
    if (!name) {
      name = sessionStorage.getItem('userId');
    }
    geRoleTree(this.$route.params.id).then(({ data }) => {
      this.tableData = data;
    });
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 方法集合
  methods: {
    // 回到上一页
    goBack() {
      this.$router.replace('/role');
    },
    // 查找菜单是否勾选
    findF(sId, tId) {
      let arr, flag;
      for (let i = 0; i < this.tableData.length; i++) { // 找第二级菜单
        const o = this.tableData[i].children;
        if (o) {
          for (let z = 0; z < o.length; z++) {
            if (o[z].id === sId) {
              arr = o[z].children;
              break;
            }
          }
        }
      }
      for (let y = 0; y < arr.length; y++) { // 找第三级菜单
        if (arr[y].id === tId) {
          flag = arr[y].flag;
          break;
        }
      }
      return flag;
    },
    // 菜单复选框
    checkSin(val) {
      console.log(val);
      const { id: rightResourceId, parentId: rightResourceSecondId, flag } = val;
      const str = `${rightResourceSecondId}_${rightResourceId}`;
      let obj = null;
      if (this.mp.has(str)) {
        obj = this.mp.get(str);
        this.mp.set(str, { ...obj, rightResourceFlag: flag });
      } else {
        this.mp.set(str, { roleId: this.$route.params.id, rightResourceSecondId, rightResourceId, rightResourceFlag: flag });
      }
    },
    // 权限复选框按钮权限
    update(val) {
      // console.log(this.$router);
      const { rightResourceSecondId, rightResourceId } = val;
      const str = `${rightResourceSecondId}_${rightResourceId}`;
      let obj = null;
      const flag = this.findF(rightResourceSecondId, rightResourceId);
      if (this.mp.has(str)) {
        obj = this.mp.get(str);
        this.mp.set(str, { ...obj, ...val, rightResourceFlag: flag });
      } else {
        this.mp.set(str, { ...val, roleId: this.$route.params.id, rightResourceFlag: flag });
      }
    },
    // 保存
    save() {
      // console.log(this.mp);
      const params = {
        roleRightButtonList: []
      };
      if (this.mp.size === 0) {
        Message.info('请先勾选权限');
        return false;
      } else {
        this.mp.forEach((value, key) => {
          // console.log(key);
          params.roleRightButtonList.push(value);
        });
        addRoleRightButton(params).then(({ data }) => {
          Message.success('角色权限保存成功');
          this.goBack();
        });
      }
    }
  }
};
</script>
<style lang='scss' scoped>
</style>
